package com.itany.corejava.code13_jdbc;

import javax.swing.plaf.nimbus.State;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import static com.itany.corejava.code13_jdbc.Test01_快速入门.JDBC_URL;

/**
 * @author MissChen
 * @date 2024年03月21日 14:41
 */
public class Test02_SQL注入 {
    public static final String JDBC_URL = "jdbc:mysql://127.0.0.1:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
    public static void main(String[] args) {
        List<User> users=login("1' or '1'='1","1' or '1'='1");
        // for(int i=0;i<users.size();i++){
        //     System.out.println(users.get(i));
        // }

        for(User user:users){
            System.out.println(user);
        }
    }

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    public static List<User> login(String username, String password) {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        List<User> users = new ArrayList<>();
        try {

            // 1.注册驱动
            Class.forName("com.mysql.jdbc.Driver");

            // 2.获取连接
            conn = DriverManager.getConnection(JDBC_URL, "root", "root");

            // 3.获取状态集
            st = conn.createStatement();

            //4.定义执行sql
            String sql = "select * from t_user where username='" + username + "' and password='" + password + "'";

            //5.执行查询操作,此时方法返回的是数据库查询的结果集，在JDBC中，数据库查询的结果集由数据库厂商封装成ResultSet对象
            rs = st.executeQuery(sql);

            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setPhone(rs.getString("phone"));
                user.setAddress(rs.getString("address"));
                users.add(user);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return users;
    }
}
